package com.ruoyi.app.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.ruoyi.app.domain.*;
import com.ruoyi.app.service.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/app")
public class AppBaseController extends BaseController {
    /**
     * 刘嘉特的Controller
     */

    @Autowired
    private IAppUsersService appUsersService;

    @GetMapping("/users/listAllUser")
    public TableDataInfo list(AppUsers appUsers) {
        startPage();
        List<AppUsers> list = appUsersService.selectAppUsersList(appUsers);
        return getDataTable(list);
    }

    @PostMapping("/users/register")
    public AjaxResult register(@RequestBody AppUsers appUsers) {
        String code = appUsers.getCode();
        if (StringUtils.isEmpty(code)) {
            return AjaxResult.error("缺少微信登录凭证 code");
        }

        // 调用微信接口换取 openid
        String appId = "wxb6cecf2c20e582ad";
        String appSecret = "74f5e7b1586bd29dc2f0c16a36879418";
        String url = "https://api.weixin.qq.com/sns/jscode2session" +
                "?appid=" + appId +
                "&secret=" + appSecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";

        try {
            RestTemplate restTemplate = restTemplate();
            String responseStr = restTemplate.getForObject(url, String.class);
            if (responseStr == null) {
                return AjaxResult.error("微信接口无响应");
            }

            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> response = objectMapper.readValue(responseStr, Map.class);

            if (response.containsKey("errcode")) {
                Integer errcode = (Integer) response.get("errcode");
                if (errcode != null && errcode != 0) {
                    String errmsg = (String) response.get("errmsg");
                    return AjaxResult.error("微信登录失败: " + (errmsg != null ? errmsg : "未知错误"));
                }
            }

            String openid = (String) response.get("openid");
            if (StringUtils.isEmpty(openid)) {
                return AjaxResult.error("未能获取 openid，请检查 code 是否有效");
            }

            // ✅ 关键步骤：根据 openid 查询用户
            AppUsers dbUser = appUsersService.selectByOpenid(openid);

            if (dbUser == null) {
                // 新用户：创建
                AppUsers newUser = new AppUsers();
                newUser.setOpenid(openid);
                newUser.setUsername(appUsers.getUsername());
                newUser.setAvatarUrl(appUsers.getAvatarUrl());
                // 映射 gender: 0=未知, 1=男, 2=女
                if (appUsers.getGender() != null) {
                    if (appUsers.getGender() == 1) {
                        newUser.setGender(1);
                    } else if (appUsers.getGender() == 2) {
                        newUser.setGender(2);
                    } else {
                        newUser.setGender(0);
                    }
                } else {
                    newUser.setGender(0);
                }
                newUser.setCreateTime(new Date());

                // 插入数据 库
                int result = appUsersService.insertUsers(newUser);
                if (result <= 0) {
                    return AjaxResult.error("用户注册失败");
                }
                dbUser = newUser; // 使用新用户
            }

            // ✅ 生成 token（示例：使用 JWT 或简单 UUID

            // 保存 token 到 Redis 或直接返回（根据你的架构）
            // 例如：redisTemplate.opsForValue().set("token:" + token, dbUser.getId(), 7, TimeUnit.DAYS);

            // 返回成功 + token
            Map<String, Object> data = new HashMap<>();
            data.put("userid", dbUser.getUserId());
            data.put("token", dbUser.getOpenid());
            data.put("username", dbUser.getUsername());
            data.put("avatarUrl", dbUser.getAvatarUrl());
            data.put("gender", dbUser.getGender());
            data.put("phone", dbUser.getPhone());
            data.put("email", dbUser.getEmail());
            data.put("studentId", dbUser.getStudentId());
            data.put("realName", dbUser.getRealName());
            data.put("college", dbUser.getCollege());
            data.put("major", dbUser.getMajor());
            data.put("idType", dbUser.getIdType());
            data.put("idNumber", dbUser.getIdNumber());
            data.put("idImage1", dbUser.getIdImage1());
            data.put("idImage2", dbUser.getIdImage2());
            data.put("graduationYear", dbUser.getGraduationYear());
            data.put("company", dbUser.getCompany());
            data.put("position", dbUser.getPosition());
            data.put("authStatus", dbUser.getAuthStatus());
            data.put("authTime", dbUser.getAuthTime());
            data.put("userType", dbUser.getUserType());
            data.put("registTime", dbUser.getRegistTime());
            data.put("code", dbUser.getCode());
            data.put("openid", dbUser.getOpenid());
            data.put("schoolcardId", dbUser.getSchoolcardId());
            return AjaxResult.success("登录成功", data);

        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return AjaxResult.error("解析微信响应失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常：" + e.getMessage());
        }
    }

    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        // 获取现有的 converters
        List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();

        // 找到 Jackson converter
        MappingJackson2HttpMessageConverter jacksonConverter = null;
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                jacksonConverter = (MappingJackson2HttpMessageConverter) converter;
                break;
            }
        }

        if (jacksonConverter != null) {
            // 添加对 text/plain 的支持
            List<MediaType> supportedMediaTypes = new ArrayList<>(jacksonConverter.getSupportedMediaTypes());
            supportedMediaTypes.add(MediaType.TEXT_PLAIN);
            jacksonConverter.setSupportedMediaTypes(supportedMediaTypes);
        }

        return restTemplate;
    }
    @PutMapping("/users/update")
    public AjaxResult edit(@RequestBody AppUsers appUsers) {
        return toAjax(appUsersService.updateAppUsers(appUsers));
    }


    /**
     * 马笑鹏的Controller
     */
    @Autowired
    private IAppDonationsService appDonationsService;

    /**
     * 查询捐赠记录管理列表
     */
    @GetMapping("/donations/list")
    public TableDataInfo list(AppDonations appDonations) {
        startPage();
        List<AppDonations> list = appDonationsService.selectAppDonationsList(appDonations);
        return getDataTable(list);
    }

    /**
     * 导出捐赠记录管理列表
     */
    @PostMapping("/donations/export")
    public void export(HttpServletResponse response, AppDonations appDonations) {
        List<AppDonations> list = appDonationsService.selectAppDonationsList(appDonations);
        ExcelUtil<AppDonations> util = new ExcelUtil<AppDonations>(AppDonations.class);
        util.exportExcel(response, list, "捐赠记录管理数据");
    }

    /**
     * 获取捐赠记录管理详细信息
     */
    @GetMapping(value = "/donations/{donationId}")
    public AjaxResult getInfo(@PathVariable("donationId") Long donationId) {
        return success(appDonationsService.selectAppDonationsByDonationId(donationId));
    }

    /**
     * 新增捐赠记录管理
     */
    @PostMapping("/donations")
    public AjaxResult add(@RequestBody AppDonations appDonations) {
        return toAjax(appDonationsService.insertAppDonations(appDonations));
    }

    /**
     * 修改捐赠记录管理
     */
    @PutMapping("/donations")
    public AjaxResult edit(@RequestBody AppDonations appDonations) {
        return toAjax(appDonationsService.updateAppDonations(appDonations));
    }

    /**
     * 删除捐赠记录管理
     */
    @DeleteMapping("/donations/{donationIds}")
    public AjaxResult remove(@PathVariable Long[] donationIds) {
        return toAjax(appDonationsService.deleteAppDonationsByDonationIds(donationIds));
    }
    /**
     * 莫培福的Controller
     */
    /**
     * 新增校友卡
     *
     * @param appUsers 用户信息
     * @return
     */
    @PostMapping("/users/alumniCard")
    public AjaxResult insertAlumniCard(@RequestBody AppUsers appUsers) {
        return toAjax(appUsersService.insertAlumniCard(appUsers));
    }

    /**
     * 王磊的Controller
     */
    @Autowired
    private IAppActivitiesService appActivitiesService;

    @Autowired
    private IAppOrganizationService appOrganizationService;

    @Autowired
    private IAppBannerService appBannerService;

    @Autowired
    private IAppNoticeService appNoticeService;

    /**
     * 获取六个校友信息
     */
    @GetMapping("/users/Card6")
    public TableDataInfo getCard6Alumni()
    {
        // 设置分页，每页6条
        PageHelper.startPage(1, 6);
        AppUsers appUsers = new AppUsers();
        // 只查询已认证的校友
        appUsers.setUserType("alumni");
        appUsers.setAuthStatus(2); // 2=已认证
        List<AppUsers> list = appUsersService.selectAppUsersList(appUsers);
        return getDataTable(list);
    }

    /**
     * 获取近三个月的三条活动
     */
    @GetMapping("/users/Activity3")
    public TableDataInfo getActivity3()
    {
        // 计算三个月前的日期
        Calendar calendar = Calendar.getInstance();
        Date endDate = calendar.getTime();
        calendar.add(Calendar.MONTH, -3);
        Date startDate = calendar.getTime();

        // 先查询最近50条活动（按创建时间或更新时间倒序），避免查询所有数据
        // 然后在内存中按开始时间过滤，这样可以提高性能
        PageHelper.startPage(1, 50, "created_at desc");
        AppActivities appActivities = new AppActivities();
        List<AppActivities> recentActivities = appActivitiesService.selectAppActivitiesList(appActivities);

        // 过滤出近三个月的活动，并按开始时间倒序排序，取前3条
        List<AppActivities> filteredList = recentActivities.stream()
                .filter(activity -> {
                    Date startTime = activity.getStartTime();
                    if (startTime == null) {
                        return false;
                    }
                    // 活动开始时间在三个月前到现在的范围内
                    return !startTime.before(startDate) && !startTime.after(endDate);
                })
                .sorted((a, b) -> {
                    // 按开始时间倒序排序
                    Date timeA = a.getStartTime();
                    Date timeB = b.getStartTime();
                    if (timeA == null && timeB == null) return 0;
                    if (timeA == null) return 1;
                    if (timeB == null) return -1;
                    return timeB.compareTo(timeA);
                })
                .limit(3)
                .collect(java.util.stream.Collectors.toList());

        return getDataTable(filteredList);
    }

    /**
     * 获取四个校友组织信息
     */
    @GetMapping("/users/Organization4")
    public TableDataInfo getOrganization4()
    {
        // 设置分页，每页4条
        PageHelper.startPage(1, 4);
        AppOrganization appOrganization = new AppOrganization();
        List<AppOrganization> list = appOrganizationService.selectAppOrganizationList(appOrganization);
        return getDataTable(list);
    }

    /**
     * 获取轮播图列表
     */
    @GetMapping("/users/Banner")
    public AjaxResult getBannerList()
    {
        AppBanner appBanner = new AppBanner();
        // 只查询状态为1（显示）的轮播图
        appBanner.setStatus(1);
        List<AppBanner> bannerList = appBannerService.selectAppBannerList(appBanner);

        // 转换为前端需要的格式
        List<Map<String, Object>> result = bannerList.stream()
                .sorted((a, b) -> {
                    // 按sort字段排序，sort越小越靠前
                    Long sortA = a.getSort() != null ? a.getSort() : Long.MAX_VALUE;
                    Long sortB = b.getSort() != null ? b.getSort() : Long.MAX_VALUE;
                    return sortA.compareTo(sortB);
                })
                .map(banner -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("id", banner.getId());
                    item.put("type", "image");
                    item.put("title", banner.getTitle() != null ? banner.getTitle() : "");
                    item.put("name", "");
                    item.put("text", "");
                    item.put("url", banner.getImageUrl() != null ? banner.getImageUrl() : "");
                    return item;
                })
                .collect(Collectors.toList());

        return AjaxResult.success(result);
    }

    /**
     * 获取公告列表
     */
    @GetMapping("/users/Notice")
    public AjaxResult getNoticeList()
    {
        AppNotice appNotice = new AppNotice();
        // 只查询状态为1（显示）的公告
        appNotice.setStatus(1);
        List<AppNotice> noticeList = appNoticeService.selectAppNoticeList(appNotice);

        // 转换为字符串数组，只取title字段
        List<String> result = noticeList.stream()
                .filter(notice -> notice.getTitle() != null && !notice.getTitle().isEmpty())
                .map(AppNotice::getTitle)
                .collect(Collectors.toList());

        return AjaxResult.success(result);
    }

    /**
     * 我的捐献记录 - 杨梦甲的Controller
     */
    @Autowired
    private IAppUserDonationsService appUserDonationsService;

    /**
     * 查询我的捐献记录列表
     */
    @GetMapping("/my_donations/list")
    public TableDataInfo listMyDonations(AppUserDonations appUserDonations) {
        startPage();
        List<AppUserDonations> list = appUserDonationsService.selectAppUserDonationsList(appUserDonations);
        return getDataTable(list);
    }

    /**
     * 导出我的捐献记录列表
     */
    @Log(title = "我的捐献记录", businessType = BusinessType.EXPORT)
    @PostMapping("/my_donations/export")
    public void exportMyDonations(HttpServletResponse response, AppUserDonations appUserDonations) {
        List<AppUserDonations> list = appUserDonationsService.selectAppUserDonationsList(appUserDonations);
        ExcelUtil<AppUserDonations> util = new ExcelUtil<>(AppUserDonations.class);
        util.exportExcel(response, list, "我的捐献记录数据");
    }

    /**
     * 获取我的捐献记录详细信息
     */
    @GetMapping(value = "/my_donations/{mydonationsId}")
    public AjaxResult getMyDonationInfo(@PathVariable("mydonationsId") Long mydonationsId) {
        return success(appUserDonationsService.selectAppUserDonationsByMydonationsId(mydonationsId));
    }

    /**
     * 新增我的捐献记录
     */
    @Log(title = "我的捐献记录", businessType = BusinessType.INSERT)
    @PostMapping("/my_donations")
    public AjaxResult addMyDonation(@RequestBody AppUserDonations appUserDonations) {
        return toAjax(appUserDonationsService.insertAppUserDonations(appUserDonations));
    }

    /**
     * 修改我的捐献记录
     */
    @Log(title = "我的捐献记录", businessType = BusinessType.UPDATE)
    @PutMapping("/my_donations")
    public AjaxResult editMyDonation(@RequestBody AppUserDonations appUserDonations) {
        return toAjax(appUserDonationsService.updateAppUserDonations(appUserDonations));
    }

    /**
     * 删除我的捐献记录
     */
    @Log(title = "我的捐献记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/my_donations/{mydonationsIds}")
    public AjaxResult removeMyDonations(@PathVariable Long[] mydonationsIds) {
        return toAjax(appUserDonationsService.deleteAppUserDonationsByMydonationsIds(mydonationsIds));
    }
}
